<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title> 
    <link href="css/mui.min.css" rel="stylesheet"/> 
    
    <link rel="stylesheet" type="text/css" href="css/chat-msg.css"/>
    <style type="text/css">
    	/*如要发送完最后一条消息就滚上去，就要设置内滚动模式*/
    	html,
		body {
			height: 100%;
			margin: 0px;
			padding: 0px;
			overflow: hidden;
			-webkit-touch-callout: none;
			-webkit-user-select: none;
		}
		.mui-content{
			height: 100%;
			padding: 44px 0px 50px 0px;
			overflow: auto;
			background-color: #eaeaea;
		}
		#msg-list {
			height: 90%;
			overflow: auto;
			-webkit-overflow-scrolling: touch;
		}
			
		footer {
			position: fixed;
			width: 100%;
			height: 50px;
			min-height: 50px;
			border-top: solid 1px #bbb;
			left: 0px;
			bottom: 0px;
			overflow: hidden;
			padding: 0px 50px;
			background-color: #fafafa;
		}
		.footer-left {
			position: absolute;
			width: 50px;
			height: 50px;
			left: 0px;
			bottom: 0px;
			text-align: center;
			vertical-align: middle;
			line-height: 100%;
			padding: 12px 4px;
		}
		.footer-left input[type="file"] {
			position: absolute;
			left: 0px;
			top: 0px;
			width: 100%;
			height: 100%;
			opacity: 0;
			cursor: pointer;
			z-index: 0;
		}
		
		.footer-right {
			position: absolute;
			width: 50px;
			height: 50px;
			right: 0px;
			bottom: 0px;
			text-align: center;
			vertical-align: middle;
			line-height: 100%;
			padding: 12px 5px;
			display: inline-block;
		}
		.footer-center {
			height: 100%;
			padding: 5px 0px;
		}
		.footer-center [class*=input] {
			width: 100%;
			height: 100%;
			border-radius: 5px;
		}
		.footer-center .input-text {
			background: #fff;
			border: solid 1px #ddd;
			padding: 10px !important;
			font-size: 16px !important;
			line-height: 18px !important;
			font-family: verdana !important;
			overflow: hidden;
		}
		.footer-center .input-sound {
			background-color: #eee;
		}
		
		footer .mui-icon {
				color: #000;
		}
		footer .mui-icon:active {
			color: #007AFF !important;
		}
		.footer-right span{
			color: #0062CC;
			line-height: 30px;
		}
		
			/*企业好友css*/
			
			 .oa-contact-cell.mui-table .mui-table-cell {
				padding: 11px 10px;
				vertical-align: middle;
			}
			
			.oa-contact-cell {
				position: relative;
				margin: -11px 0;
			}
	
			.oa-contact-avatar {
				width: 75px;
			}
			.oa-contact-avatar img {
				border-radius: 50%;
			}
			.oa-contact-content {
				width: 100%;
			}
			.oa-contact-name {
				margin-right: 10px;
			}
			
    </style>
</head>
<body>
	<header class="mui-bar mui-bar-nav">
		<a href="sessionupdate.html" class=" mui-icon mui-icon-left-nav mui-pull-left"></a>
		<h1 class="mui-title">微架构</h1>
	</header>
	<div class="mui-content">
		<div  id="msg-list"></div>
	</div>

	<footer>
		<div class="footer-left">
			<i id='msg-choose-img' class="mui-icon mui-icon-image"></i>
		</div>
		
	
		
		<div class="footer-center">
			
			<textarea id='console' type="text" class='input-text'>
				
				
			</textarea>
			
		</div>
		<div class="footer-right">
			<span id='msg-send-text'>发送</span>
		</div>
	</footer>
	
	<script src="js/mui.min.js"></script>
	<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>

	
	
	<script type="text/javascript" charset="UTF-8">
      	
		var ui = {
			content: mui('.mui-content'[0]),
			msgList: mui('#msg-list')[0],
			footer: mui('footer')[0],
			msgChooseImg: mui("#msg-choose-img")[0],
			msgInputText: mui('#console')[0],
			msgSendText: mui('#msg-send-text')[0]
		}
      	
		         
		
		
      	//我的名字和id
      	 var userid=localStorage.getItem("loginName");
      	 var myName=localStorage.getItem("myName");
      	
		
		
		ui.msgInputText.value = '';	
		var Chat = {};
		var message="";
        var obj = null;
		var myPhoto="";
		
		//var qun="";//最新的信息
		var imgData = "";
		var imgData2 = "";
        Chat.socket = null;
		//Chat.initialize();
        Chat.connect = (function (host) {
            if ('WebSocket' in window) {
                Chat.socket = new WebSocket(host);
            } else if ('MozWebSocket' in window) {
                Chat.socket = new MozWebSocket(host);
            } else {
                console.log('Error: WebSocket is not supported by this browser.');
                return;
            }
		
		

            Chat.socket.onopen = function () {
                console.log('Info: WebSocket connection opened.');
                ui.msgSendText.addEventListener('tap',function(){ 
                        Chat.sendMoreMessage();
                    	
                })
            };

			
			
            Chat.socket.onclose = function () {
                
                console.log('Info: WebSocket closed.');
            };
			
            Chat.socket.onmessage = function (message) {
            	var strs= new Array(); //定义一数组 
				strs=message.data.split(","); //字符分割 
				for (i=0;i<strs.length ;i++ ) 
				{ 
					
				}
				
				mui.ajax({
							type: "post",
							url: "http://113.71.26.27:8080/tpl/phone/getPhoneImg",
							async: true,
							data: {
								loginName: strs[0]
							},
							dataType: "json",
							timeout: 2000,
							crossDomain: true,
							success: function(data) {
						if(strs[1]=='photo'){
		            			var photoUrl="http://113.71.26.27:8080/tpl/public/uploadImage/peopleLogo/"+data.imgUrl;
		            			var firendsMessge="<div class='mui-slider-cell'>"
		            				+"<h5>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+data.name+":"+"</h5>"
									+"<div class='oa-contact-cell mui-table '>"	
		                				+"<div class='oa-contact-avatar mui-table-cell'>"
											+"<img style='width:40px;height:40px;' src='"+photoUrl+"' />"
										+"</div>"
									+"</div>"
									+"<div class='oa-contact-cell mui-table '>"
									+"<div class='oa-contact-content mui-table-cell' style=' top:-50px;left:60px;'>"																	
											+"<img style='width:auto;height:auto;' src='data:image/png;base64,"+strs[2]+"'/>"	
									+"</div>"
									+"</div>"
								+"</div>"
							+"</div>";
		                	localStorage.setItem("qun",firendsMessge);
							Console.log(firendsMessge)			
							}else if(strs[1]=='text'){
            		       		
				            	var photoUrl="http://113.71.26.27:8080/tpl/public/uploadImage/peopleLogo/"+data.imgUrl;
				            	var firendsMessge="<div class='mui-slider-cell'>"
				            				+"<h5>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+data.name+":"+"</h5>"
										+"<div class='oa-contact-cell mui-table '>"	
											+"<div class='oa-contact-avatar mui-table-cell'>"
												+"<img style='width:40px;height:40px;' src='"+photoUrl+"' />"
											+"</div>"
											+"<div class='oa-contact-content mui-table-cell' >"																	
													+"<h5 style='text-align: left; font-size:20px ; '>"+strs[2]+"</h5>"
											+"</div>"
										+"</div>"
									+"</div>";
								localStorage.setItem("qun",firendsMessge);
				                Console.log(firendsMessge);
				               			
				               }			
							},
							error: function(xhr, type, errorThrown) {
								plus.nativeUI.toast(errorThrown);
							}
						});
				
            	
            	
            	
            	
            }
        });

        
        Chat.close= function () {
          Chat.socket.onclose();  
        };

       
		
		getImgByLoginName(userid);
		
        Chat.sendMoreMessage = (function () {
            //Chat.connect('ws://113.71.26.27:8080/tpl/websocket/' + userid);//
             message =ui.msgInputText.value.replace(new RegExp('\n', 'gm'), '<br/>');//消息;
            if (message != ''&&imgData=='') {
                obj = {
                    message: message,
                    from: userid,
                    to: -1,
                    type:"text"
                };
                Chat.socket.send(JSON.stringify(obj));
                ui.msgInputText.value = '';	
                
                var photoUrl="http://113.71.26.27:8080/tpl/public/uploadImage/peopleLogo/"+myPhoto;
               
                var myMessge="<div class='mui-slider-cell'>"
                			+"<h5 style='text-align: right;'>"+":"+myName+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h5>"
						+"<div class='oa-contact-cell mui-table '>"							
							+"<div class='oa-contact-content mui-table-cell' style='text-align: right;'>"									
									+"<h5 style='text-align: right; font-size:20px ; '>"+message+"</h5>"									
							+"</div>"							
							+"<div class='oa-contact-avatar mui-table-cell' style='text-align: right;'>"
								+"<img style='width:40px;height:40px;' src='"+photoUrl+"' />"
							+"</div>"
						+"</div>"
					+"</div>";
               
                Console.log(myMessge);
            }else if(imgData!=""){
            	obj = {
                    message: imgData,
                    from: userid,
                    to: -1,
                    type:"photo"
                };
                Chat.socket.send(JSON.stringify(obj));
                //ui.msgInputText.value = '';	
                
                var photoUrl="http://113.71.26.27:8080/tpl/public/uploadImage/peopleLogo/"+myPhoto;
               
                var myImg="<div class='mui-slider-cell'>"
                			+"<h5 style='text-align: right;'>"+":"+myName+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h5>"
                			+"<div class='oa-contact-cell mui-table '>"	
                				+"<div class='oa-contact-avatar mui-table-cell' style='text-align: right;'>"
									+"<img style='width:40px;height:40px;' src='"+photoUrl+"' />"
								+"</div>"
							+"</div>"
							+"<div class='oa-contact-cell mui-table '>"
							+"<div class='oa-contact-content mui-table-cell' style='text-align: right; top:-50px;right:60px;'>"									
									+"<img style='width:auto;height:auto;' src='data:image/png;base64,"+imgData+"'/>"									
							+"</div>"							
							+"</div>"
						
					+"</div>";
               
                Console.log(myImg);
            	
            }
        });
		





        var Console = {};

        Console.log = (function (message) {
            var console = document.getElementById('msg-list');
            var p = document.createElement('div');
           
            p.style.wordWrap = 'break-word';
            p.innerHTML = message;
            console.appendChild(p);
            while (console.childNodes.length > 25) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        });

        

        document.addEventListener("DOMContentLoaded", function () {
            var noscripts = document.getElementsByClassName("noscript");
            for (var i = 0; i < noscripts.length; i++) {
                noscripts[i].parentNode.removeChild(noscripts[i]);
            }
        }, false);

		mui.plusReady(function() {
			console.info("连接服务器");
      	 	Chat.connect('ws://113.71.26.27:8080/tpl/websocket/' + userid);//
      	 	var qun=localStorage.getItem("qun");
      	 	//Console.log(qun);
			});

			
            
		
    	
    	
		// 发送文本消息
    	ui.msgSendText.addEventListener('tap',function(){
    			
    				Chat.sendMoreMessage();
    				imgData="";
    			
    		
    		
    		
    	})
    	
    	// 选择图片
    	ui.msgChooseImg.addEventListener('tap',function(){
    		galleryImg();
    		
    	})
    	
		// 解决长按“发送”按钮，导致键盘关闭的问题；
		ui.msgSendText.addEventListener('touchstart', function(event) {
			msgInputTextFocus();
			event.preventDefault();
		});
		ui.msgSendText.addEventListener('touchmove', function(event) {
			msgInputTextFocus();
			event.preventDefault();
		});
		
		// 输入框监听事件
    	ui.msgInputText.addEventListener('input', function(event) {
    		msgInputTextFocus();
			ui.footer.style.height = this.scrollHeight + 'px';
		});
    	
    	// 调整窗口
    	window.addEventListener('resize', function() {
			msgScrollTop();
		}, false);
    	
    	
    	
    	
    	
    	
    	//本地相册选择 
			function galleryImg() {
				plus.gallery.pick(function(a) {
					plus.io.resolveLocalFileSystemURL(a, function(entry) {
						plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
							root.getFile("head.png", {}, function(file) {
								//文件已存在 
								file.remove(function() {
									console.log("file remove success");
									entry.copyTo(root, 'head.png', function(e) {
											var e = e.fullPath + "?version=" + new Date().getTime();
											//document.getElementById("head-img").src = e;
											var image = new Image();
											image.src = e;
											image.onload = function() {
												imgData = getBase64Image(image);
												imgData2 = getBase64Image(image);
												mui.toast("选择图片成功");
											}
											
											
										},
										function(e) {
											console.log('copy image fail:' + e.message);
										});
								}, function() {
									console.log("delete image fail:" + e.message);
								});
							}, function() {
								//文件不存在 
								entry.copyTo(root, 'head.png', function(e) {
										var path = e.fullPath + "?version=" + new Date().getTime();
										document.getElementById("head-img").src = path;
										var image = new Image();
										image.src = path;
										image.onload = function() {
											imgData = getBase64Image(image);
											
										}
									},
									function(e) {
										console.log('copy image fail:' + e.message);
									});
							});
						}, function(e) {
							console.log("get _www folder fail");
						})
					}, function(e) {
						console.log("读取拍照文件错误：" + e.message);
					});
				}, function(a) {}, {
					filter: "image"
				})
			};

			//将图片压缩转成base64 
			function getBase64Image(img) {
				var canvas = document.createElement("canvas");
				var width = img.width;
				var height = img.height;
				// calculate the width and height, constraining the proportions 
				if(width > height) {
					if(width > 200) {
						height = Math.round(height *= 200 / width);
						width = 200;
					}
				} else {
					if(height > 200) {
						width = Math.round(width *= 200 / height);
						height = 200;
					}
				}
				canvas.width = width; /*设置新的图片的宽度*/
				canvas.height = height; /*设置新的图片的长度*/
				var ctx = canvas.getContext("2d");
				ctx.drawImage(img, 0, 0, width, height); /*绘图*/
				var dataURL = canvas.toDataURL("image/png", 0.8);
				return dataURL.replace("data:image/png;base64,", "");
			}
    	
    	
		
		// 消息滚动
		var msgScrollTop = function(){
			ui.msgList.scrollTop = ui.msgList.scrollHeight + ui.msgList.offsetHeight;
			//ui.msgList.input=message;
		}
		
		// 获得输入框键盘焦点
		var msgInputTextFocus = function(){
			ui.msgInputText.focus();
    		setTimeout(function() {
				ui.msgInputText.focus();
			}, 150);
		}
		
		// 强制弹出软键盘
		var showKeyboard = function() {
			if (mui.os.ios) {
				var webView = plus.webview.currentWebview().nativeInstanceObject();
				webView.plusCallMethod({
					"setKeyboardDisplayRequiresUserAction": false
				});
			} else if(mui.os.android) {
				var Context = plus.android.importClass("android.content.Context");
			    var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
			    var main = plus.android.runtimeMainActivity();
			    var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
			    imm.toggleSoftInput(0,InputMethodManager.SHOW_FORCED);
			}
		};
		
			/**
		 * 重写返回事件
		 */
		mui.back = function(){
			
			window.location.href = "sessionupdate.html";
		}
		
		//获取头像
		function getImgByLoginName(id) {
				var network = true;
				
				if(mui.os.plus) {
					mui.plusReady(function() {
						if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
							network = false;
						}
					});
				}
				
					if(network) {
						console.log('网络正常,正在发送请求...');

						mui.ajax({
							type: "post",
							url: "http://113.71.26.27:8080/tpl/phone/getPhoneImg",
							async: true,
							data: {
								loginName: id
							},
							dataType: "json",
							timeout: 2000,
							crossDomain: true,
							success: function(data) {
								
									myPhoto=data.imgUrl;
									
								
								
									
								
							},
							error: function(xhr, type, errorThrown) {
								plus.nativeUI.toast(errorThrown);
							}
						});

					} else {
						mui.toast("当前网络不给力，请稍后再试...");
					}
				
			};
		
		
		
    </script>
</body>
</html>